package com.xjt.wx_admin.security;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.xjt.wx_admin.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

@Slf4j
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        int code = HttpStatus.UNAUTHORIZED.value();
        Object errorMessage = Optional.ofNullable(request.getAttribute("errorMessage")).orElse(authException.getMessage());
        if (request.getAttribute("code")!=null){
            code = (int) request.getAttribute("code");
        }
        response.setStatus(code);
        ServletUtils.renderString(response, JSON.toJSONString(R.failed(errorMessage.toString()).setCode(code)));
    }

}